<template>
  <div>
    <h2 class="text-center" style="margin-top: 100px;">{{loginType}}</h2>
    <form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
        >
          提交
        </van-button>
      </div>
    </form>
  </div>
</template>

<script>
import { Field, Button } from 'vant';
import { login } from '../api/user';
import bus from '../utils/event_bus';

export default {
  components: {
    [Field.name]: Field,
    [Button.name]: Button
  },
  props: {
    type: {
      default: 'mobile'
    }
  },
  computed: {
    loginType() {
      return this.type === 'mobile' ? '手机号登录' : '资金账号登录';
    }
  },
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    onSubmit(e) {
      e.preventDefault();
      if(this.username && this.password) {
        login({
          username: this.username,
          password: this.password,
          loginType: this.type
        }).then(data => {
          bus.$emit('login', data);
          this.$router.back();
        })
      } else {
        this.$dialog.alert({
          message: '请输入用户名和密码'
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
form {
  position: absolute;
  top: 50%;
  width: 100%;
  transform: translateY(-50%);
}
</style>
